package com.listview.test;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class TodoList extends ListActivity {
	
	private ArrayList<TodoItem> todoItems;
	private EditText editText;
	private ArrayAdapter<TodoItem> aa;
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        editText = (EditText)findViewById(R.id.text_input);
        todoItems = new ArrayList<TodoItem>();
        aa = new ArrayAdapter<TodoItem>(this, android.R.layout.simple_list_item_1, todoItems);
        getListView().setAdapter(aa);
        
        editText.setOnKeyListener(new OnKeyListener(){
        	@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(event.getAction() == KeyEvent.ACTION_DOWN){
					if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
						TodoItem newItem;
						newItem = new TodoItem(editText.getText().toString());
						todoItems.add(0, newItem);
						editText.setText("");
						aa.notifyDataSetChanged();
						return true;
					}
				}
				return false;
			}
        });
    }
    
    static class TodoItem{
    	public String task;
    	public Date created;
    	
    	public TodoItem(String task){
    		this.task = task;
    		this.created = new Date(java.lang.System.currentTimeMillis());
    	}
    	
    	public String toString(){
    		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    		String dateString = sdf.format(created);
    		return "(" + dateString + ") " + task; 
    	}
    }
}
